package ru.autofan.logic;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import ru.autofan.domain.Car;
import ru.autofan.domain.CarFoto;
import ru.autofan.domain.CarInfo;
import ru.autofan.form.AddCarForm;
import ru.autofan.logic.enums.CarSortType;
import ru.autofan.logic.support.FotoTypeExtracter;
import ru.autofan.secure.AuthRoleSupport;
import ru.autofan.secure.Restricted;
import ru.autofan.view.CarBean;

public class CarService extends BasicService {

	@Deprecated // Delete MultipartFile
	@Restricted(authRoleSupport = AuthRoleSupport.USER)
	@Transactional(propagation = Propagation.REQUIRED)
	public void addCar(AddCarForm form) throws IOException {
		Car car = new Car();
		CarInfo carInfo = new CarInfo();
		carInfo.setDescription(form.getDescription());
		carInfo.setPrice(form.getPrice());
		car.setCarInfo(carInfo);

		if (form.getUploadedFiles().size() > 0) {
			Set<CarFoto> fotos = new HashSet<CarFoto>(form.getUploadedFiles()
					.size());
			for (MultipartFile file : form.getUploadedFiles()) {
				CarFoto foto = new CarFoto();
				foto.setData(file.getBytes());
				foto.setCar(car);
				foto.setType(new FotoTypeExtracter().extract(file));
				fotos.add(foto);
			}
			car.setFotos(fotos);
		}
		car.setOwner(getServiceLocator().getService(LoginService.class)
				.getLoggedUser());
		getDomainFactory().save(car);
	}

	private String getCarField(CarSortType sortType) {
		switch (sortType) {
		case BY_ID:
			return "id";
		case BY_NAME:
			return "carInfo.description";
		case BY_PRICE:
			return "carInfo.price";
		default:
			return "id";
		}
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public Long getCarsPages() {
		EntityPageFetcher fetcher = new EntityPageFetcher(getDaoSupporter(),
				getDomainFactory());
		
		return fetcher.getEntityPages(Car.class);
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public List<CarBean> getCarsByPage(Long page, String sort) throws Exception {
		EntityPageFetcher fetcher = new EntityPageFetcher(getDaoSupporter(),
				getDomainFactory());
		if (StringUtils.isBlank(sort)) {
			sort = CarSortType.BY_ID.name();
		}
		sort = getCarField(CarSortType.valueOf(sort.toUpperCase()));
		return fetcher.fetch(CarWarpFactory.class, Car.class, CarBean.class,
				page, sort);
	}
}
